from django.http import HttpResponse
import outland.list.models as om
from django.shortcuts import render_to_response

def getSearchResult(queryDict):
    query_void = True
    
    m_name = queryDict['m_name']
    pmin = queryDict['pmin']
    pmax = queryDict['pmax']
    category = queryDict['category']
    category_full = queryDict['category_full']
    
    print "okay"
    menuList= om.Menu.objects
    if len(m_name.strip()) > 0:
        menuList = menuList.filter(name__contains=m_name)
        query_void = False
    if pmin >= 0 and pmax >= 0:
        menuList = menuList.filter(price__gte=pmin)
        menuList = menuList.filter(price__lte=pmax)
        query_void = False
    if category_full == 'false':
        menuList = menuList.filter(shop__category__name__in=category)
        
    return (menuList, query_void)

def handleQuery(request):
    try:
        query = {}
        query['m_name'] = request.GET.get('q', '')
        m_name = request.GET.get('q', '')
        query['pmin'] = int(request.GET.get('pmin', -1))
        query['pmax'] = int(request.GET.get('pmax', -1))
        query['category'] = ((request.GET.get('category', '')).strip()).split()
        category = query['category']
        query['category_full'] = request.GET.get('category_full', 'true')      

        (menuList, query_void) = getSearchResult(query)
        
        if (not query_void) and len(menuList) == 0:
            return render_to_response('search/NoSearchResult.html',{'m_name': m_name.encode('utf-8'), 'pmin':query['pmin'], 'pmax':query['pmax']})
        
        if query_void:
            return HttpResponse(m_name)
        else:
	    return render_to_response('search/SearchResult.html',{'m_name':m_name.encode('utf-8'), 'menuList': menuList})
    except:
        return HttpResponse("Error.<br /> category:" + str(category) +
        '<br />m_name:' + m_name)

def mainPage(request):
    query = request.GET.get('q', '')
    categoryList = om.ShopCategory.objects.filter()
    
    if query == '':
        return render_to_response('search/BaseSearch.html',{'categoryList': categoryList})
    else:
        menus = om.Menu.objects.filter(name__contains=query)
        '''
        queryDict = {}
        queryDict['m_name'] = query.encode('utf-8')
        queryDict['pmin'] = -1
        queryDict['pmax'] = -1
        queryDict['category'] = ''.strip().split()
        queryDict['category_full'] = 'true'
        (menuList, query_void) = getSearchResult(queryDict)
        '''
        return render_to_response('search/SearchResult_full.html',{'categoryList': categoryList, 'm_name':query.encode('utf-8'), 'menuList':menus})
